import 'package:aero_frisbee/app/model/af_edit_user_param_model/af_edit_user_param_model.dart';
import 'package:aero_frisbee/app/model/af_user_info_model/af_user_info_model.dart';
import 'package:aero_frisbee/app/state/app_cache_state.dart';
import 'package:aero_frisbee/core/extension/string_ext.dart';
import 'package:aero_frisbee/core/tools/af_log_manager.dart';
import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:aero_frisbee/pages/modues/message/pages/message/message_detail/viwe_model/af_message_detail_view_model.dart';
import 'package:aero_frisbee/pages/modues/mine/profile/view_model/af_profile_view_model.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class AfCustomerServiceScreen extends ConsumerStatefulWidget {
  const AfCustomerServiceScreen({Key? key}) : super(key: key);
  @override
  AfCustomerServiceScreenState createState() => AfCustomerServiceScreenState();
}

class AfCustomerServiceScreenState
    extends ConsumerState<AfCustomerServiceScreen> {
  final _textController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    final loginUserInfo = ref.watch(curlUserInfoProvider)?.userInfoModel;
    final userInfo = ref
        .watch(getUserInfoFutureProvider(userId: loginUserInfo?.userId ?? ''))
        .maybeWhen(
          orElse: () => null,
          data: (data) => data,
        );

    ref.listen(getUserInfoFutureProvider(userId: loginUserInfo?.userId ?? ''),
        (previousData, newData) {
      final userInfo =
          newData.maybeWhen(data: ((data) => data), orElse: () => null);
      if (userInfo != null) {
        _textController.text = userInfo.nickname ?? '';
      }
    });

    final curEditUserParamState = ref.watch(curEditUserParamServiceProvider);
    ref.listen(updateProfileSubmitServiceProvider, (previousData, newData) {
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        ref.invalidate(getUserInfoFutureProvider);
        "update success".toast(onDismiss: () {
          Navigator.of(context).maybePop();
        });
      }
    });

    return Scaffold(
      appBar: AppBar(
        leading: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            Navigator.of(context).maybePop();
          },
          child: Align(
            alignment: Alignment.centerLeft,
            child: Padding(
              padding: const EdgeInsets.only(
                left: 20,
              ),
              child: Assets.icons.iconMineBack.image(width: 25),
            ),
          ),
        ),
      ),
      body: SafeArea(
        child: Column(
          children: [
            const SizedBox(
              height: 68,
            ),
            Align(
              alignment: Alignment.topCenter,
              child: SizedBox(
                height: 98,
                child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    ///选择头像
                    _pickImage();
                  },
                  child: AspectRatio(
                    aspectRatio: 1,
                    child: FractionallySizedBox(
                      widthFactor: 1,
                      heightFactor: 1,
                      child: Stack(
                        children: [
                          Container(
                            decoration: const BoxDecoration(),
                            padding: const EdgeInsets.all(12),
                            child: LayoutBuilder(
                              builder: (BuildContext context,
                                  BoxConstraints constraints) {
                                return ClipRRect(
                                  borderRadius: BorderRadius.circular(
                                      constraints.maxHeight / 2),
                                  child: AspectRatio(
                                    aspectRatio: 1,
                                    child: curEditUserParamState.avatarPath !=
                                                null &&
                                            curEditUserParamState
                                                .avatarPath!.isNotEmpty
                                        ? Image.asset(
                                            curEditUserParamState.avatarPath!,
                                            fit: BoxFit.cover,
                                          )
                                        : CachedNetworkImage(
                                            imageUrl: userInfo?.avatarUrl ?? '',
                                            fit: BoxFit.fill,
                                            placeholder: (context, url) =>
                                                const Material(
                                              color: Color(0xffF2F5F9),
                                              child: Center(
                                                child: SizedBox(
                                                  width: 25,
                                                  height: 25,
                                                  child:
                                                      CircularProgressIndicator(
                                                    strokeWidth: 2,
                                                    color: Color(0xffADADAD),
                                                    backgroundColor:
                                                        Colors.white,
                                                  ),
                                                ),
                                              ),
                                            ),
                                            errorWidget:
                                                (context, url, error) =>
                                                    const Icon(Icons.error),
                                          ),
                                  ),
                                );
                              },
                            ),
                          ),
                          Positioned(
                            bottom: 13,
                            right: 13,
                            child: Assets.icons.iconUpdateAvatarBtn
                                .image(width: 26),
                          )
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ),
            const SizedBox(
              height: 32,
            ),
            AfCustomerRowItem(
              title: 'Nick Name',
              value: userInfo?.nickname ?? '',
              valueWidget: SizedBox(
                height: 35,
                width: 120,
                child: Align(
                  alignment: Alignment.topRight,
                  child: TextField(
                    textAlign: TextAlign.right,
                    controller: _textController,
                    onChanged: (value) {
                      ref
                          .read(curEditUserParamServiceProvider.notifier)
                          .updateName(value);
                    },
                    decoration: const InputDecoration(
                      contentPadding: EdgeInsets.only(bottom: 15),
                      border: InputBorder.none,
                    ),
                  ),
                ),
              ),
            ),
            AfCustomerRowItem(
              title: 'Date of Birth',
              value: curEditUserParamState.birthDate != null
                  ? '${curEditUserParamState.birthDate}'
                  : '${userInfo?.birthday}',
              onTap: () {
                if (curEditUserParamState.birthDate != null) {
                  _selectDate(context,
                      selectedDate: curEditUserParamState.birthdayDate);
                } else {
                  _selectDate(context, selectedDate: userInfo!.birthdayDate);
                }
              },
            ),
            const Spacer(),
            GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                if (curEditUserParamState.isEdited) {
                  final param = ref.read(curEditUserParamServiceProvider);
                  ref
                      .read(updateProfileSubmitServiceProvider.notifier)
                      .updateProfileSubmit(param: param, userInfo: userInfo!);
                }
              },
              child: Container(
                decoration: BoxDecoration(
                  color: curEditUserParamState.isEdited
                      ? const Color(0xffDDFB6C)
                      : const Color(0xffDDFB6C).withOpacity(0.5),
                  borderRadius: BorderRadius.circular(25),
                ),
                padding:
                    const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                margin: const EdgeInsets.symmetric(horizontal: 25),
                child: Center(
                  child: Text(
                    'Submit',
                    style: TextStyle(
                      color: curEditUserParamState.isEdited
                          ? const Color(0xff202020)
                          : const Color(0xff202020).withOpacity(0.5),
                      fontWeight: FontWeight.normal,
                      fontSize: 14,
                    ),
                    textAlign: TextAlign.center,
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                  ),
                ),
              ),
            ),
            const SizedBox(
              height: 40,
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _selectDate(BuildContext context,
      {required DateTime selectedDate}) async {
    final DateTime picked = await showCupertinoModalPopup(
      context: context,
      builder: (BuildContext builder) {
        return Container(
          height: 240.0,
          color: CupertinoColors.white,
          child: Column(
            children: [
              SizedBox(
                height: 200.0,
                child: CupertinoDatePicker(
                  mode: CupertinoDatePickerMode.date,
                  maximumYear: DateTime.now().year - 18,
                  initialDateTime: selectedDate,
                  onDateTimeChanged: (DateTime newDate) {
                    final retStr = DateFormat('yyyy-MM-dd').format(newDate);

                    ref
                        .read(curEditUserParamServiceProvider.notifier)
                        .updateBirthDay(retStr);
                  },
                ),
              ),
            ],
          ),
        );
      },
    );

    if (picked != selectedDate) {
      setState(() {
        selectedDate = picked;
      });
    }
  }

  _pickImage() async {
    AFLogPvManger.stat(page: AFLogPages.editAvatar);
    if (!await Permission.photos.isGranted) {
      var permissionStatus = await Permission.photos.request();
      if (permissionStatus != PermissionStatus.granted) {
        "You have not authorised this permission.".toast();
        return;
      }
    }
    final temporaryPath = await getTemporaryDirectory();
    final ImagePicker picker = ImagePicker();
    picker.pickImage(source: ImageSource.gallery).then((file) {
      if (file != null) {
        var cachePath =
            "${temporaryPath.path}/${DateTime.now().millisecondsSinceEpoch}.jpg";
        FlutterImageCompress.compressAndGetFile(
          file.path,
          cachePath,
          quality: 40,
        ).then(
          (value) {
            if (value != null) {
              ref
                  .read(curEditUserParamServiceProvider.notifier)
                  .updateAvatar(value.path);
            }
          },
        ).onError((error, stackTrace) {
          print(error);
        });
      }
    });
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final userInfo = ref.read(curlUserInfoProvider)?.userInfoModel;
      if (userInfo != null) {
        _textController.text = userInfo.nickname ?? '';
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didUpdateWidget(AfCustomerServiceScreen oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}

class AfCustomerRowItem extends StatelessWidget {
  const AfCustomerRowItem({
    Key? key,
    required this.title,
    this.value = '',
    this.valueWidget,
    this.onTap,
  }) : super(key: key);

  final String title;
  final String value;
  final Widget? valueWidget;
  final Function()? onTap;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: onTap,
      child: Container(
        decoration: BoxDecoration(
          color: const Color(0xffF7F8FA),
          borderRadius: BorderRadius.circular(12),
        ),
        margin: const EdgeInsets.symmetric(horizontal: 32, vertical: 10),
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              title,
              style: TextStyle(
                color: const Color(0xff000000).withOpacity(0.3),
                fontWeight: FontWeight.normal,
                fontSize: 12,
              ),
              textAlign: TextAlign.left,
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
            ),
            valueWidget ??
                SizedBox(
                  height: 35,
                  child: Align(
                    alignment: Alignment.centerRight,
                    child: Text(
                      value,
                      style: const TextStyle(
                        color: Color(0xff404040),
                        fontWeight: FontWeight.normal,
                        fontSize: 16,
                      ),
                      textAlign: TextAlign.right,
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                    ),
                  ),
                ),
          ],
        ),
      ),
    );
  }
}
